package com.huishu.tcm.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huishu.tcm.entity.Annex7Patient;
import com.huishu.tcm.entity.User;
import com.huishu.tcm.service.Annex7PatientService;
import com.huishu.tcm.service.UserService;
import com.huishu.tcm.util.AESUtil;
import com.huishu.tcm.util.Constants;
import com.huishu.tcm.util.exception.TcmException;
import com.huishu.tcm.util.exception.TcmExceptionEnum;
import com.huishu.tcm.vo.PageVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "自我健康管理健康信息表")
@RestController
@RequestMapping("/api/annex7Patient")
public class Annex7PatientController extends BaseController<Annex7PatientService> {

    /**
     * 根据id查询数据
     * @param id
     * @return
     */
    @ApiOperation(value = "根据主键查询一条数据", notes = "根据主键查询一条数据")
    @RequestMapping(method = RequestMethod.GET)
    public Annex7Patient get(@RequestParam String id) throws TcmException {
        QueryWrapper<Annex7Patient> wrapper = new QueryWrapper<>();
        wrapper.eq("id",id);
        return service.getOne(wrapper);
    }

    /**
     * 查询数据列表
     * @return
     */
    @ApiOperation(value = "根据筛选条件查询数据列表", notes = "根据筛选条件查询数据列表")
    @RequestMapping(value = "/list",method = RequestMethod.POST)
    public List<Annex7Patient> list(@RequestBody Annex7Patient v) throws TcmException {
        QueryWrapper<Annex7Patient> queryWrapper = service.getQueryWrapper(v);
        return service.list(queryWrapper);
    }

    /**
     * 分页查询数据列表
     * @param pageVo
     * @return
     */
    @ApiOperation(value = "根据筛选条件分页查询数据列表", notes = "根据筛选条件分页查询数据列表")
    @RequestMapping(value = "/page", method = RequestMethod.POST)
    public Page<Annex7Patient> page(@RequestBody PageVo<Annex7Patient> pageVo) throws TcmException {
        Annex7Patient v = pageVo.getEntity();
        QueryWrapper<Annex7Patient> wrapper = service.getQueryWrapper(v);
        Page<Annex7Patient> page = new Page<>(pageVo.getPage(),pageVo.getLimit());
        page = service.page(page,wrapper);
        return page;
    }

    /**
     * 添加
     * @param v
     * @return
     */
    @ApiOperation(value = "添加一条数据",notes = "添加一条数据")
    @RequestMapping(method = RequestMethod.POST)
    public boolean save(@RequestBody Annex7Patient v) throws Exception {
        QueryWrapper<Annex7Patient> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("patient_id",v.getPatientId());
        queryWrapper.orderByDesc("number");
        List<Annex7Patient> list = service.list(queryWrapper);
        if(ObjectUtil.isEmpty(list)){
            v.setNumber(1);
        }else{
            v.setNumber(list.get(0).getNumber() + 1);
        }
        Date now = new Date();
        User loginUser = getLoginUser();
        v.setCreateTime(now);
        v.setCreateUser(loginUser.getName());
        v.setUpdateTime(now);
        v.setUpdateUser(loginUser.getName());
        return service.save(v);
    }

    /**
     * 根据主键更新
     * @param v
     * @return
     */
    @ApiOperation(value = "根据主键更新数据",notes = "根据主键更新数据")
    @RequestMapping(method = RequestMethod.PUT)
    public boolean update(@RequestBody Annex7Patient v) throws Exception {
        Date now = new Date();
        v.setUpdateTime(now);
        v.setUpdateUser(getLoginUser().getName());
        QueryWrapper<Annex7Patient> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", v.getId());
        return service.update(v,queryWrapper);
    }


    /**
     * 根据主键删除
     * @param id
     * @return
     */
    @ApiOperation(value = "根据主键删除数据",notes = "根据主键删除数据")
    @RequestMapping(method = RequestMethod.DELETE)
    public boolean removeById(@RequestParam Integer id){
        QueryWrapper<Annex7Patient> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        return service.remove(wrapper);
    }

    @Resource
    UserService userService;

    @ApiOperation(value = "根据医疗机构信息将自我健康管理健康信息表导出到excel", notes="根据医疗机构信息将自我健康管理健康信息表导出到excel")
    @GetMapping(value = "/exportExcel", params = {"institutionId"})
    public void exportExcel(Integer institutionId) throws TcmException, IOException {
        // 根据医疗机构id查询患者列表
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("institution_id",institutionId);
        userQueryWrapper.eq("role", Constants.USER_ROLE_PATIENT);
        userQueryWrapper.orderByDesc("id");
        List<User> patientList = userService.list(userQueryWrapper);
        if(ObjectUtil.isEmpty(patientList)){
            throw new TcmException(TcmExceptionEnum.DATA_NOT_EXISTS);
        }
        // 根据患者id列表查询 自我健康管理健康信息表 数据
        List<Integer> patientIdList = patientList.stream().map(User::getId).collect(Collectors.toList());
        QueryWrapper<Annex7Patient> Annex7PatientQueryWrapper = new QueryWrapper<>();
        Annex7PatientQueryWrapper.in("patient_id",patientIdList);
        Annex7PatientQueryWrapper.orderByDesc("patient_id");
        Annex7PatientQueryWrapper.orderByDesc("number");
        List<Annex7Patient> Annex7PatientList = service.list(Annex7PatientQueryWrapper);
        if(ObjectUtil.isEmpty(Annex7PatientList)){
            throw new TcmException(TcmExceptionEnum.DATA_NOT_EXISTS);
        }
        // 生成EXCEL数据
        ExcelWriter writer = ExcelUtil.getWriter(true);
        Sheet sheet = writer.getSheet();
        List<List<String>> rows = new ArrayList<>();
        List<String> row = CollUtil.newArrayList("姓名","性别","年龄","身份证号","手机号","是否了解改善生活方式对改善糖尿病前期有积极意义","教授的中医防病技巧是否能熟练运用","是否能熟练使用血糖仪自测血糖","是否注意合理膳食、均衡营养","是否按照“500111法则”或“手掌法则”执行情况","推荐中医食疗措施执行情况","有氧运动方式","有氧运动频次","有氧每次运动时长","阻抗运动方式","阻抗运动频次","阻抗每次运动时长","中医运动方式","中医运动频次","中医每次运动时长","其他中医运动管理措施执行情况","体重减轻","主动控制饮食","主动增强运动","中医减重执行情况","睡眠时间6-8小时","是否按处方落实调理","是否按照中医血糖控制处方严格执行","第几次录入","录入时间");
        rows.add(row);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (User patient : patientList) {
            AESUtil.userInfoDesensitization(patient);
            for (Annex7Patient annex7Patient: Annex7PatientList) {
                if (annex7Patient.getPatientId().equals(patient.getId())) {
                    row = new ArrayList<>();
                    row.add(patient.getName());
                    row.add(patient.getGender());
                    row.add(String.valueOf(patient.getAge()));
                    row.add(patient.getIdNum());
                    row.add(patient.getTelNum());
                    row.add(annex7Patient.getA211());
                    row.add(annex7Patient.getA212());
                    row.add(annex7Patient.getA213());
                    row.add(annex7Patient.getA221());
                    row.add(annex7Patient.getA222());
                    row.add(annex7Patient.getA223());
                    row.add(annex7Patient.getA231());
                    row.add(annex7Patient.getA232());
                    row.add(annex7Patient.getA233());
                    row.add(annex7Patient.getA234());
                    row.add(annex7Patient.getA235());
                    row.add(annex7Patient.getA236());
                    row.add(annex7Patient.getA237());
                    row.add(annex7Patient.getA238());
                    row.add(annex7Patient.getA239());
                    row.add(annex7Patient.getA2310());
                    row.add(annex7Patient.getA241());
                    row.add(annex7Patient.getA242());
                    row.add(annex7Patient.getA243());
                    row.add(annex7Patient.getA244());
                    row.add(annex7Patient.getA25());
                    row.add(annex7Patient.getA26());
                    row.add(annex7Patient.getA27());
                    row.add(String.valueOf(annex7Patient.getNumber()));
                    row.add(sdf.format(annex7Patient.getCreateTime()));
                    rows.add(row);
                }
            }
        }
        writer.write(rows);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition","attachment;filename=export.xlsx");
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        writer.close();
        IoUtil.close(out);
    }

    @ApiOperation(value = "查询本周是否填写个人报告", notes = "小程序端查询本周是否填写个人报告")
    @GetMapping(value = "/queryIsReportThisWeek", params = {"patientId"})
    public Boolean queryIsReportThisWeek(Integer patientId){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE ,-7);
        QueryWrapper<Annex7Patient> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("patient_id",patientId);
        queryWrapper.gt("create_time",sdf.format(calendar.getTime()));
        List<Annex7Patient> list = service.list(queryWrapper);
        return ObjectUtil.isNotEmpty(list);
    }
}